package com.xyw.his00.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xyw.his00.anno.OptionLog;
import com.xyw.his00.dto.AreaDTO;
import com.xyw.his00.dto.OrderDTO;
import com.xyw.his00.entity.ResponseData;
import com.xyw.his00.mapper.AreaMapper;
import com.xyw.his00.mapper.RegisterMapper;
import com.xyw.his00.pojo.dbpojo.Register;
import com.xyw.his00.service.Impl.dbImpl.AreaServiceImpl;
import com.xyw.his00.service.Impl.dbImpl.RegisterServiceImpl;
import com.xyw.his00.service.dbservice.AreaService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@CrossOrigin
@RestController
@RequestMapping("/register/")

public class RegisterController {
    @Resource
    private RegisterServiceImpl registerService;//挂号服务
    @Resource
    private RegisterMapper registerMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private AreaServiceImpl areaService;

    //根据id获取病历号
    @RequestMapping("getOrderNo{id}")
    public String getOrderNo(@RequestParam int id){
        System.out.println("--------getOrderNo方法");
        return registerService.register(id);
    }
    //页面加载获取信息
    @RequestMapping("getRegistFeeAndCount")
    public List<OrderDTO> getRegistFeeAndCount(@RequestParam(value = "hao") int id){
        System.out.println("挂号页面加载成功");
     //在registermapper中构建复杂查询返回对象
    return  registerService.getOrderDTO(id);
    }
    //处理挂号逻辑
    @OptionLog
    @Transactional
    @PostMapping(value = "submit")
   public ResponseData submit(
                              @RequestParam("orderNo")String caseNumber,
                              @RequestParam("patientName")String realName,
                              @RequestParam("patientGender")String gender,
                              @RequestParam("identifyNumber")String cardNumber,
                              @RequestParam("birthday")String birthday,
                              @RequestParam("age")int age,
                              @RequestParam("dataAge") String ageType,
                              @RequestParam("address")String homeAddress,
                              @RequestParam("date1") String visitDate,
                              @RequestParam("wuType") String noon,
                              @RequestParam("deptId") int deptId,
                              @RequestParam("employeeId") int employeeId,
                              @RequestParam("hao") int registLevelId,
                              @RequestParam("jieMethod")  int settleCategoryId,
                              @RequestParam("delivery") String isBook,
                              @RequestParam("moneyMethod")String registMethod,
                              @RequestParam("moneyMust") BigDecimal registMoney
                             )
            {


                Register register = new Register(
                    caseNumber, realName, gender, cardNumber,
                       LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd")), age, ageType, homeAddress,
                       LocalDateTime.parse(visitDate,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) , noon, deptId, employeeId, registLevelId,
                        settleCategoryId, isBook, registMethod,1,registMoney);
                registerService.getBaseMapper().insert(register);
                System.out.println(register.getId());
                System.out.println("submit方法执行成功");
                if(register==null){
                    return ResponseData.ERROR;
                }else{
                    return ResponseData.SUCCESS;
                }
    }
    //处理挂号收费
    //根据病历号搜索获取病人信息
    @GetMapping("selectOrderPatientInfo")//todo:只能选择患者列表的第一个进行挂号
    public List<Map<String, Object>> selectOrderPatientInfo(
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "realName", required = false) String userName) {
        System.out.println("----selectOrderPatientInfo");
        List<Map<String,Object>> list=new ArrayList<>();
        // 创建查询条件包装器
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","real_name", "gender", "card_number", "age","case_number");
        queryWrapper.eq("visit_state",1);
        // 检查并设置查询条件
        if (orderNo == null || orderNo.equals(" ")) {
            // 如果病历号为空或仅包含空格，则根据真实姓名查询
            if (userName != null && !userName.equals("　")) {
                queryWrapper.like("real_name", "%"+userName.trim()+"%");
            } else {
                // 如果病历号和真实姓名都为空或仅包含空格，则不执行查询（或抛出异常）
                throw new IllegalArgumentException("病历号和真实姓名都为空或仅仅包含空格，不执行查询");
            }
        } else {
            // 如果病历号不为空，则根据病历号查询，可能同时根据真实姓名查询
            queryWrapper.like("case_number", "%"+orderNo.trim()+"%");
            if (userName != null && !userName.equals(" ")) {
                queryWrapper.like("real_name", "%"+userName.trim()+"%");
            }
        }

        // 执行查询并返回结果
        return registerMapper.selectMaps(queryWrapper);
    }
    @RequestMapping("selectOrderPatientInfoList")
    public List<Map<String,Object>> selectOrderPatientInfoList(){
        List<Map<String,Object>> list=new ArrayList<>();
        // 创建查询条件包装器
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","real_name", "gender", "card_number", "age","case_number");
       return registerMapper.selectMaps(queryWrapper);
    }
    //处理挂号收费
    //根据病历号或者姓名模糊查询搜索获取第一个病人信息，如果有多条信息，传名字就优先名字，传病历号就优先病历号
    @GetMapping("selectOrderPatient")//todo:只能选择患者列表的第一个进行挂号

    public Register selectOrderPatient(
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "realName", required = false) String userName) {
        System.out.println("----selectOrderPatient");

        // 创建查询条件包装器
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","real_name", "gender", "card_number", "age","case_number");
        queryWrapper.eq("visit_state",1);
        // 检查并设置查询条件
        if (orderNo == null || orderNo.equals(" ")) {
            // 如果病历号为空或仅包含空格，则根据真实姓名查询
            if (userName != null && !userName.equals("　")) {
                queryWrapper.like("real_name", "%"+userName.trim()+"%");

            } else {
                // 如果病历号和真实姓名都为空或仅包含空格，则不执行查询（或抛出异常）
                throw new IllegalArgumentException("病历号和真实姓名都为空或仅仅包含空格，不执行查询");
            }
        } else {
            // 如果病历号不为空，则根据病历号查询，可能同时根据真实姓名查询
            queryWrapper.like("case_number", "%"+orderNo.trim()+"%");

            if (userName != null && !userName.equals(" ")) {
                queryWrapper.like("real_name", "%"+userName.trim()+"%");
            }
        }
        queryWrapper.orderByAsc("visit_date");
        List<Register> list=registerMapper.selectList(queryWrapper);
        //如果集合不为空返回第一个对象
        if(!list.isEmpty()){
            return list.get(0);
        }else {
            return registerMapper.selectOne(queryWrapper);
        }
    }
    //处理挂号收费
    //根据病历号或者姓名精确查询搜索获取一个病人信息，如果有多条信息，传名字就优先名字，传病历号就优先病历号
    @GetMapping("selectOrderPatientSuper")//todo:只能选择患者列表的第一个进行挂号
    public Register selectOrderPatientSuper(
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "realName", required = false) String userName) {
        System.out.println("----selectOrderPatientSuper");
        // 创建查询条件包装器
        QueryWrapper<Register> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("visit_state",1);
        // 检查并设置查询条件
        if (orderNo == null || orderNo.equals(" ")) {
            // 如果病历号为空或仅包含空格，则根据真实姓名查询
            if (userName != null && !userName.equals("　")) {
                queryWrapper.eq("real_name", userName.trim());
            } else {
                // 如果病历号和真实姓名都为空或仅包含空格，则不执行查询（或抛出异常）
                throw new IllegalArgumentException("病历号和真实姓名都为空或仅仅包含空格，不执行查询");
            }
        } else {
            // 如果病历号不为空，则根据病历号查询，可能同时根据真实姓名查询
            queryWrapper.eq("case_number",orderNo );
            if (userName != null && !userName.equals(" ")) {
                queryWrapper.eq("real_name",userName );
            }
        }
       return registerMapper.selectOne(queryWrapper);
    }
}
